/**
 * Copyright 2021 xieyuanhui
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.milantiejiang.tuto;

import android.util.Log;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 对每次的发送请请求都加锁，以控制每一次请求（发，收）的原子性
 */
public class ClientThread implements Runnable {
    private final String TAG = getClass().getSimpleName();
    IRspListener mListener=null;
    private byte[] mMsg = null;
    private ReentrantLock mLock = new ReentrantLock(true);


    public ClientThread(){
    }

    public void setRspListener(IRspListener listener){
        mListener=listener;
    }
    public void setmMsg(byte[] mMsg) {
        this.mMsg = mMsg;
    }

    @Override
    public void run() {
        mLock.lock();
        try {
            Socket socket = null;
            try {
                socket = new Socket(CommContent.IP,CommContent.PORT);
            } catch (IOException e) {
                e.printStackTrace();
            }
            InputStream input = null;
            DataOutputStream doutput = null;
            OutputStream output = null;
            DataInputStream dinput = null;
            try {
                socket.setSoTimeout(20 * 1000);
                output = socket.getOutputStream();
                doutput = new DataOutputStream(output);
                //向服务端发送数据 REQ
                doutput.write(mMsg, 0, mMsg.length);
                Log.i(TAG, Thread.currentThread().getName() + " 客户端发送消息："+ Utils.bytesToHexString(mMsg));
                doutput.flush();

                input = socket.getInputStream();
                dinput = new DataInputStream(input);
                byte[] readbuf = new byte[1024];
                dinput.read(readbuf);
                int dataLen= Utils.bytes2Int_LE(Utils.subByte(readbuf,4,7));
                Log.i(TAG,"dataLen:"+dataLen);
                String dataStr= Utils.hexBytes2Str(Utils.subByte(readbuf,8,dataLen));
                Log.i(TAG, "客户端收到消息："+dataStr);
                mListener.onRspMsg(socket,dataStr);
            } catch (SocketTimeoutException e) {
                Log.i(TAG, "连接超时");
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    input.close();
                    dinput.close();
                    output.close();
                    doutput.close();
                    Log.i(TAG, "Stream close");
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }finally {
            mLock.unlock();
        }
    }
}
